<!--
 * @Author: lp
 * @Date: 2022-01-16 18:51:37
 * @LastEditTime: 2022-06-21 17:32:11
 * @LastEditors: lp 654528967@qq.com
 * @Description: app主入口
 * @FilePath: //nien-vue3-admin//src//App.vue
-->
<template>
  <el-config-provider :locale="locale" :size="setting.size">
    <router-view />
  </el-config-provider>
</template>
<script lang="ts" setup>
import { ref, onBeforeUnmount, getCurrentInstance, computed, onErrorCaptured } from 'vue'
import zhCn from 'element-plus/lib/locale/lang/zh-cn'
import en from 'element-plus/lib/locale/lang/en'
import { ElConfigProvider } from 'element-plus'
import userStore from '@/store/modules/user'
import { getToken, getExpiresIn } from '@/utils/auth'
import useSetting from '@/store/modules/setting'

const setting = useSetting()
const { proxy } = getCurrentInstance() as any
const refreshTime = ref<number | undefined>(undefined)
const refreshLock = ref(false)
const user = userStore()
const locale = computed(() => {
  switch (proxy.$i18n.locale) {
    case 'en':
      return en
    case 'zh-cn':
      return zhCn
    default:
      return zhCn
  }
})
const refreshToken = () => {
  refreshTime.value = window.setInterval(() => {
    // debugger
    if (getToken() == null) return
    const expiresIn = getExpiresIn()
    if (expiresIn <= 1000 && !refreshLock.value) {
      refreshLock.value = true
      user.handRefreshToken().catch(() => {
        clearInterval(refreshTime.value)
      })
      refreshLock.value = false
    }
    user.setExpiresIn(expiresIn - 10)
  }, 10000)
}
refreshToken()
onBeforeUnmount(() => {
  clearInterval(refreshTime.value)
})
onErrorCaptured((err, component, info) => {
  console.log(err, component, info)
  return false
})
</script>
